package cn.fl.capital.controller;

import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.KeyValueVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.mid.core.framework.page.Pager;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.DecimalUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.capital.condition.CapFundOutLogQueryCondition;
import cn.fl.capital.constant.CapitalConstant;
import cn.fl.capital.service.ICapFundOutLogService;
import cn.fl.capital.service.ICapFundService;
import cn.fl.capital.vo.CapFundOutLogVO;
import cn.fl.capital.vo.CapFundVO;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.project.vo.PrjQuatPrpsCfgDVO;
import cn.fl.system.constant.SysLogConstant;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import net.sf.json.JSONArray;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: 客户资金转出记录表 控制层
 */
@Controller
@RequestMapping("/capital/capFundOutLog")
public class CapFundOutLogController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(CapFundOutLogController.class);
	
	/**
	 * CapFundOutLog 服务层BEAN
	 */
	@Autowired
	private ICapFundOutLogService capFundOutLogService;
    @Autowired
    private ICapFundService capFundService;
	
	/**
	 * 到列表页面
	 */
	@RequestMapping(value = "/toListPage.do", method = { RequestMethod.GET})
	public ModelAndView toListPage(HttpServletRequest request, HttpServletResponse response) {
		BaseLogUtils.info(logger, "toListPage", "加载CapFundOutLog列表页面.",CurrentThreadContext.getCurrentUserName());
		ModelAndView mav = new ModelAndView("capital/capFundOutLog/capFundOutLogList");
		return mav;
	}
	
	/**
	 * 到新增页面
	 */
	@RequestMapping(value = "/toAddPage.do", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView toAddPage(HttpServletRequest request, HttpServletResponse response) {
		BaseLogUtils.info(logger, "toAddPage", "加载CapFundOutLog Add页面.",CurrentThreadContext.getCurrentUserName());
		ModelAndView mav = new ModelAndView("capital/capFundOutLog/capFundOutLogModify");
		//this.prepare(request,mav);
		return mav;
	}

	/**
	 * 到修改页面
	 */
	@RequestMapping(value = "/toModifyPage.do", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView toModifyPage(HttpServletRequest request, HttpServletResponse response) {
		BaseLogUtils.info(logger, "toModifyPage", "加载CapFundOutLog Modify页面.",CurrentThreadContext.getCurrentUserName());
		ModelAndView mav = new ModelAndView("capital/capFundOutLog/capFundOutLogModify");
		//this.prepare(request,mav);
		
		String id=request.getParameter("id");
		CapFundOutLogVO capFundOutLogVO = this.capFundOutLogService.selectById(Long.valueOf(id));
        mav.addObject("capFundOutLogVO", capFundOutLogVO);
		return mav;
	}
	
	//加载数据字典数据、传值等 ？
    public void prepare(HttpServletRequest request,ModelAndView mav){
    	
    }

	/**
	 * 初始化列表
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/initList.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object initCapFundOutLogList(HttpServletRequest request, HttpServletResponse response) {
		String currentPage = request.getParameter("page");
		String pageSize = request.getParameter("pagesize");
		Pager page = new Pager();
		if (StringUtils.isNotEmpty(currentPage)) {
			page.setCurrentPage(Integer.parseInt(currentPage));
		}

		if (StringUtils.isNotEmpty(pageSize)) {
			page.setEveryPage(Integer.parseInt(pageSize));
		}

		CapFundOutLogQueryCondition qc = new CapFundOutLogQueryCondition();
		//TODO 设置查询条件？
		String searchName = request.getParameter("searchName");
		if (StringUtils.isNotEmpty(searchName)) {
			
		}
		page.setCondition(qc);

		BaseLogUtils.info(logger, "initCapFundOutLogList", "初始化CapFundOutLog列表页面数据.DATA:"+JSONObject.toJSONString(page), CurrentThreadContext.getCurrentUserName());
		Pager pager = this.capFundOutLogService.searchListPage(page);
		List<CapFundOutLogVO> list = (List<CapFundOutLogVO>) pager.getResultList();
		ListPageVO<CapFundOutLogVO> listPage = new ListPageVO<CapFundOutLogVO>(list, pager.getTotalCount());
		return listPage;
	}

	/**
	 * 删除数据
	 */
	@RequestMapping(value = "/removeByIds.do", method = {RequestMethod.POST })
	@ResponseBody
	public DataResultVO removeCapFundOutLogByIds(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String ids = request.getParameter("ids");
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_DELETE_SUCC);
        if (StringUtils.isEmpty(ids)) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
            BaseLogUtils.info(logger, "removeCapFundOutLogByIds", "删除CapFundOutLog数据,主键参数为空!", CurrentThreadContext.getCurrentUserName());
            return result;
        }

        List<Long> idsList = new ArrayList<Long>();
        JSONArray idsArray = JSONArray.fromObject(ids);
        for (Object object : idsArray) {
            idsList.add(Long.valueOf(object.toString()));
        }
		
		try {
			boolean success = this.capFundOutLogService.removeByIds(idsList);
			if(!success){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_DELETE_FAIL);
				BaseLogUtils.info(logger, "removeCapFundOutLogByIds", "删除CapFundOutLog数据失败,ID:"+idsList.toString(), CurrentThreadContext.getCurrentUserName());
			}
			BaseLogUtils.info(logger, "removeCapFundOutLogByIds", "删除CapFundOutLog数据成功,ID:"+idsList.toString(), CurrentThreadContext.getCurrentUserName());
		} catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.info(logger, "removeCapFundOutLogByIds", "删除CapFundOutLog数据失败,ID:"+idsList.toString()+".ERROR:"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		} catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "removeCapFundOutLogByIds", "删除CapFundOutLog数据失败,系统错误.ID:"+idsList.toString()+".ERROR:"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}

	/**
	 * 得到一条记录
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getById.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object getCapFundOutLogById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.info(logger, "getCapFundOutLogById", "获取CapFundOutLog数据,主键参数为空.", CurrentThreadContext.getCurrentUserName());
			return result;
		}
		
		try {
			CapFundOutLogVO vo = this.capFundOutLogService.selectById(Long.valueOf(id));
			if(null == vo){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_QUERY_DATA_IS_EMPTY);
				BaseLogUtils.info(logger, "getCapFundOutLogById", "获取CapFundOutLog数据不存在,ID:"+id, CurrentThreadContext.getCurrentUserName());
			}
			result.setData(vo);
			BaseLogUtils.info(logger, "getCapFundOutLogById", "获取CapFundOutLog数据成功,ID:"+id, CurrentThreadContext.getCurrentUserName());
		}catch(BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.info(logger, "getCapFundOutLogById", "获取CapFundOutLog数据失败,ID:"+id+".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch(Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "getCapFundOutLogById", "获取CapFundOutLog数据失败,系统错误.ID:"+id+".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}

	/**
	 * 新增
	 */
	@RequestMapping(value = "/add.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object addCapFundOutLog(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_ADD_SUCC);
		CapFundOutLogVO entity = null;//获取参数
		try {
			entity = this.getRequestParamForCapFundOutLog(request);//获取参数
			Long id = this.capFundOutLogService.add(entity);
			result.setData(id);
			BaseLogUtils.info(logger, "addCapFundOutLog", "新增CapFundOutLog数据成功,ID:"+id+".DATA:"+JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR+ex.getMessage());
			BaseLogUtils.info(logger, "addCapFundOutLog", "新增CapFundOutLog数据失败.DATA:"+JSONObject.toJSONString(entity)+".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR+ex.getMessage());
			BaseLogUtils.error(logger, "addCapFundOutLog", "新增CapFundOutLog数据失败,系统错误.DATA:"+JSONObject.toJSONString(entity)+".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}

	/**
	 * 修改
	 */
	@RequestMapping(value = "/modify.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object modifyCapFundOutLog(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES,SysLogConstant.LOG_CMM_UPDATE_SUCC);
		CapFundOutLogVO entity = null;
		try {
			entity = this.getRequestParamForCapFundOutLog(request);
			if(entity.getId()==null){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
				BaseLogUtils.info(logger, "modifyCapFundOutLog", "修改CapFundOutLog信息,主键参数为空！.", CurrentThreadContext.getCurrentUserName());
				return result;
			}

			boolean success = this.capFundOutLogService.modify(entity);
			if(!success){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_UPDATE_FAIL);
				BaseLogUtils.info(logger, "modifyCapFundOutLog", "修改CapFundOutLog数据失败.DATA:"+JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
				return result;
			}
			BaseLogUtils.info(logger, "modifyCapFundOutLog", "修改CapFundOutLog数据成功.DATA:"+JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR+ex.getMessage());
			BaseLogUtils.info(logger, "modifyCapFundOutLog", "修改CapFundOutLog数据失败.DATA:"+JSONObject.toJSONString(entity)+".ERROR:"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR+ex.getMessage());
			BaseLogUtils.error(logger, "modifyCapFundOutLog", "修改CapFundOutLog数据失败,系统错误.DATA:"+JSONObject.toJSONString(entity)+".ERROR:"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}
	
	/**
	 * 获取请求参数
	 * @param request 请求
	 * @return 
	 */
	private CapFundOutLogVO getRequestParamForCapFundOutLog(HttpServletRequest request) throws BaseException{
		//获取参数
		String id = request.getParameter("id");//主键
		String fundId = request.getParameter("fundId");//资金ID(CAP_FUND表主键)
		String outTypCd = request.getParameter("outTypCd");//转出类型（CAP0024）1.退款 2.来款错误3.其他
		String outTm = request.getParameter("outTm");//转出时间
		String outAmt = request.getParameter("outAmt");//转出金额
		String optUsrId = request.getParameter("optUsrId");//操作人ID
		String optUsrNm = request.getParameter("optUsrNm");//操作人名称
		String outRem = request.getParameter("outRem");//备注

		//验证参数并赋值
		CapFundOutLogVO entity = new CapFundOutLogVO();
 		//entity.setFundId(fundId);//资金ID(CAP_FUND表主键)
 		//entity.setOutTypCd(outTypCd);//转出类型（CAP0024）1.退款 2.来款错误3.其他
 		//entity.setOutTm(outTm);//转出时间
 		//entity.setOutAmt(outAmt);//转出金额
 		//entity.setOptUsrId(optUsrId);//操作人ID
 		//entity.setOptUsrNm(optUsrNm);//操作人名称
 		//entity.setOutRem(outRem);//备注
	
//		if (StringUtils.isBlank(name)) {
//            throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "名称不能为空.");
//      }
//      if (StringUtils.isNotBlank(num)) {
//          if (!StringUtils.isUnsignedNumeric(num)) {
//                throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "请填写正确的数字.");
//          }
//      }

		Date tm=new Date();
		if (StringUtils.isNotBlank(id)) {
			entity.setId(Long.valueOf(id));
			entity.setMdfTm(tm);
			entity.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
		}else{
			entity.setCrtTm(tm);
			entity.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
			//entity.setCrtUsrOrgCd(CurrentThreadContext.getCurrentOrgCd());//当前用户组织机构代码
            //entity.setOrgCd(CurrentThreadContext.getCurrentBuOrgCd());//事业部组织机构代码
		}
		
		return entity;
	}
	
	

	/**
	 * 初始化列表
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/initfundList.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object initFundOutLogList(HttpServletRequest request, HttpServletResponse response) {
		
		String currentPage = request.getParameter("page");
		String pageSize = request.getParameter("pagesize");
		Pager page = new Pager();
		if (StringUtils.isNotEmpty(currentPage)) {
			page.setCurrentPage(Integer.parseInt(currentPage));
		}
		if (StringUtils.isNotEmpty(pageSize)) {
			page.setEveryPage(Integer.parseInt(pageSize));
		}
		CapFundOutLogQueryCondition qc = new CapFundOutLogQueryCondition();
		//TODO 设置查询条件？
		String funid = request.getParameter("fund_Id");
		String fundAmt = request.getParameter("fundAmt");
		if (StringUtils.isNotEmpty(funid)) {
			qc.setFundId(Long.parseLong(funid));
		}
		page.setCondition(qc);
		ListPageVO<CapFundOutLogVO> listPage=null;
		
		Pager pager = this.capFundOutLogService.searchListPage(page);
		List<CapFundOutLogVO> list = (List<CapFundOutLogVO>) pager.getResultList();
	   if (CollectionUtils.isNotEmpty(list)) {
		   /**处理多条转出资金核算逻辑*/
		   //资金总共值
		    Long parseLong = Long.parseLong(fundAmt);
			Long outAmt = list.get(0).getOutAmt();
			double sub = DecimalUtils.sub(parseLong.doubleValue(), outAmt.doubleValue());
			//记录表转出资金剩余
		   for(CapFundOutLogVO capFundOutLogVO : list) {
			   Long fundId = capFundOutLogVO.getFundId();
			   capFundOutLogVO.setFundIdCdNm("ZJ"+String.valueOf(fundId));
			   capFundOutLogVO.setOutAmtfund(Long.valueOf(Double.valueOf(sub).longValue()));
			}
		   
			listPage = new ListPageVO<CapFundOutLogVO>(list, pager.getTotalCount());
			BaseLogUtils.info(logger, "capFundOutLog/initfundList", "初始化CapFundOutLog列表页面数据.DATA:"+JSONObject.toJSONString(page), CurrentThreadContext.getCurrentUserName());
			return listPage;
		}else{
	       int  ipagecount=0;
	       List<CapFundOutLogVO>  newdata =new ArrayList<CapFundOutLogVO>();
	       CapFundOutLogVO  Outvo =new CapFundOutLogVO();
		   Outvo.setFundId(Long.parseLong(funid));
		   Outvo.setOptUsrNm(CurrentThreadContext.getCurrentUserName());
		   Outvo.setOptUsrId(CurrentThreadContext.getCurrentUserId());
		   Outvo.setIsNO(0);//标识这条数据是数据库没有的数据
		   Outvo.setOutAmt(Long.parseLong(fundAmt));
		   Outvo.setOutAmtfund(Long.parseLong(fundAmt));//剩余可转资金
		   Outvo.setFundIdCdNm("ZJ"+funid);
		   newdata.add(Outvo);
	       listPage = new ListPageVO<CapFundOutLogVO>(newdata, ipagecount);
	       return listPage;
		}
	}
	
	/**
	 * 新增
	 */
	@RequestMapping(value = "/addModifyFrozen.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object addonModifyFrozen(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		DataResultVO result = null;
		CapFundOutLogVO entity = null;//获取参数
		try {
			//获取参数
			String feeInfo = request.getParameter("Param");
			//解析Info
			List<CapFundOutLogVO> CapFundOutLogVOList = new ArrayList<CapFundOutLogVO>();
			if (StringUtils.isNotBlank(feeInfo)) {
				CapFundOutLogVOList = JSON.parseArray(feeInfo, CapFundOutLogVO.class);
			}
			//后面会支持多条转出
			Long id=0l;
			for (CapFundOutLogVO capFundOutLogVO : CapFundOutLogVOList) {
				if(StringUtils.isNotEmpty(capFundOutLogVO.getId())){
					boolean modify = this.capFundOutLogService.modify(capFundOutLogVO);
					result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_UPDATE_SUCC);
				    }else{
					id = this.capFundOutLogService.add(capFundOutLogVO);
					result =new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_ADD_SUCC);
					if(id!=0l){
						 List<CapFundVO> idsList = new ArrayList<CapFundVO>();
						 CapFundVO enty=null;
				            for (CapFundOutLogVO CapFundOutLogVO : CapFundOutLogVOList) {
				            	enty = new CapFundVO();
				            	enty.setId(CapFundOutLogVO.getFundId());
				            	enty.setFundStatusCd(CapitalConstant.CODE_CAP_FUND_STS_CD_6);//已转出
				            	enty.setMdfUsrId(CurrentThreadContext.getCurrentUserId());//用户id
				            	idsList.add(enty);
				            }
				     boolean success_start = this.capFundService.ModifyListFundCstInfo(idsList);
					  }
				}
			}
			BaseLogUtils.info(logger, "addModifyFrozen", "新增CapFundOutLog数据成功,ID:"+id+".DATA:"+JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR+ex.getMessage());
			BaseLogUtils.info(logger, "addModifyFrozen", "新增CapFundOutLog数据失败.DATA:"+JSONObject.toJSONString(entity)+".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR+ex.getMessage());
			BaseLogUtils.error(logger, "addModifyFrozen", "新增CapFundOutLog数据失败,系统错误.DATA:"+JSONObject.toJSONString(entity)+".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}
}

